package com.itheima.CSM_bacK.aabServices;

import com.itheima.CSM_bacK.aabServices.Serv.GenerateFileService;
import com.itheima.CSM_bacK.aacMapper.CheckSetmealMapper;
import com.itheima.pojo.Entity.CheckGroup;
import com.itheima.pojo.Entity.CheckItem;
import com.itheima.pojo.Entity.Setmeal;
import com.itheima.pojo.VO.VOMOBsGet;
import com.itheima.pojo.VO.vovo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GenerateFileImpl implements GenerateFileService {
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Autowired
    private CheckSetmealMapper checkSetmealMapper;
    @Value("${freemarker.out.path}")
    private String outPath;

    @Override
    public void generateFile(String name) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        try {
            // 获取模板
            Template template = configuration.getTemplate(name+".ftl");
            // 组装数据
            Map<String, Object> map = new HashMap<>();
//            List<Map> mapList = new ArrayList<>();
            List<Setmeal> kks = checkSetmealMapper.getMeal();
            List<vovo> vos = new ArrayList<>();
            kks.forEach(kk -> {
                vovo vo = new vovo();
                vo.setId(kk.getId());
                vo.setName(kk.getName());
                vo.setAge(kk.getAge());
                vo.setImg(kk.getImg());
                vo.setRemark(kk.getRemark());
                vos.add(vo);
            });
            map.put("setmealList",kks);

            // 创建输出文件
            File file = new File(outPath+name+".html");
            // 将数据和模板组装起来
            try (Writer writer = new FileWriter(file);) {
                template.process(map,writer);
            } catch (TemplateException e) {
                throw new RuntimeException(e);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
